import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
import fs from 'fs'
// create an axios instance
let file = process.cwd() + '\\config.json' // 文件路径
console.log('file',file)
let basePath = 'http://121.36.52.112:8081'
try {
  console.log('文件',fs.readFileSync(file, 'utf-8'))
} catch (err) {
  Message.error('配置文件(软件安装根目录下的config.json)出错')
  // 出错了
}
basePath = JSON.parse(fs.readFileSync(file, 'utf-8')).url
console.log('basePath',basePath)


// create an axios instance
const service = axios.create({
  headers: {
    'content-type': 'application/json'
  },
  baseURL: basePath, // 打包地址
  // baseURL: 'http://192.168.0.157:8081', // 测试地址
  // baseURL: 'http://121.36.52.112:8081', // 线上地址
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (response.status && response.status === 200) {
      // 判断数据是否请求成功
      if (res.success) {
        // 返回正确的结果(then接受数据)
        return res
      } else if (res.msg === '验证错误请重新登录') { // 未登录或登录已失效
        MessageBox('登录失效, 请重新登录！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          
        store.dispatch('user/logout')
        router.go(0)
        // router.push(`/login?redirect=${router.fullPath||''}`)
        }).catch(() => {
        })
      } else { // 其他错误提示
        // Message({
        //   message: res.message || 'Error',
        //   type: 'error',
        //   duration: 5 * 1000
        // })
        return res
      }
    } else {
      response.reject()
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
